<?php
/** 
 * Used to allow the enduser to make a quick and easy install of Klarnas payment modules.
 * 
 * @author Klarna
 */
class klarna_install extends oxAdminView {
	/**
	 * Current class template name.
	 * @var string
	 */
	protected $_sThisTemplate = 'klarna_install.tpl';
	private $kutil = null;
	private $oDB = null;
	private $shopId = null;
	
	/**
	 * Adds extra information that is used in the view.
	 * 
	 * @Override
	 * @return returns the template file.
	 */
	public function render() {
		parent::render();
		
		if(!$this->kutil) {
			$this->kutil = oxNew('klarnautil');
		}
		if(!$this->oDB) {
			$this->oDB = oxDb::getDb(true);
		}
		if(!$this->shopId) {
			$myConfig = $this->getConfig();
			$this->shopId = $myConfig->getShopId();
		}
		
		$updater = oxNew('klarnaupdater');
		$installer = $this->kutil->getInstallObject();
		$status = true;
		if($updater->checkIfUpdateIsNeeded()) {
			$updater->doUpdate();
		} else {
			$status = $this->install($installer);
		}
		$this->_aViewData['status'] = $status;
		
		//A better alogrithm for when the tmp folder needs to be emptied needs to be created.
		$kconfig = $this->kutil->getKlarnaConfig();
		$temp = explode(':', $kconfig->klarnaconfig__currversion->value);
		$sql = "SELECT CURRVERSION FROM klarnaconfig WHERE OXID = '" . $this->shopId . "';";
		$currSysVersion = $this->oDB->getOne($sql);
		$this->_aViewData['cleanTmp'] = false;
		if(!$updater->checkIfUpdateIsNeeded() && $currSysVersion != $kconfig->klarnaconfig__currversion->value) {
			$this->_aViewData['cleanTmp'] = true;
		}
		$this->_aViewData['showcurrver'] = !$updater->checkIfUpdateIsNeeded();
		$this->_aViewData['currver'] = $temp[2];
		
		$baseurl = "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']).'/modules/klarna/images';
		$baseurl = str_replace('/admin', '', $baseurl);
		$this->_aViewData['logo'] = $baseurl . '/klarna.png';
		
		$this->_aViewData['saveconfig'] = $installer->klarnainstall__saveconfig->value;
		$this->_aViewData['defaultcountry'] = $this->defaultCountry($installer);
		$this->_aViewData['kconfig'] = $this->kutil->getKlarnaConfig();
		
		$aCurrencies = oxConfig::getInstance()->getConfigParam('aCurrencies');
		$mainCurr = '';
		$currencies = array();
		if(!empty($aCurrencies)) {//$currenciesToAdd
			foreach ($aCurrencies as $aCurrenciesName) {
				$currencyInfo = preg_split('/[@]/', $aCurrenciesName);
				
				if($currencyInfo[0] == 'SEK' || $currencyInfo[0] == 'NOK' || $currencyInfo[0] == 'DKK') {
					$currencies[] = $aCurrenciesName;
				}
				//Begins at one, as it contains a space.
				$mainCurr = (substr($currencyInfo[1], 1, 4) == '1.00') ? $aCurrenciesName : $mainCurr;
			}
		}
		$this->_aViewData['maincurr'] = $mainCurr; 
		$this->_aViewData['acurrencies'] = $currencies;
		
		$temp = $this->kutil->getDefaultCountries();
		$oDB = oxDb::getDb(true);
		foreach ($temp as $key => $value) {
			$sql = "SELECT OXTITLE from oxcountry WHERE OXISOALPHA2 = '$key';";
			$temp[$key] = $oDB->getOne($sql);
		}
		$this->_aViewData['thedefaultcountrys'] = $temp;
		
		$this->_aViewData['isDone'] = $installer->isDone();

		return $this->_sThisTemplate;
	}
	
	protected function install($installer) {
		try {
			if(	$installer->klarnainstall__createtables->value && 
				$installer->klarnainstall__insertpayments->value && 
				$installer->klarnainstall__addusergroups->value && 
				$installer->klarnainstall__addcountries->value && 
				$installer->klarnainstall__addshippingtypes->value && 
				$installer->klarnainstall__amoduleinoxconfig->value) {
				
				return true;	
			}
			
			$status = array('createtables' => false,
							'insertpayments' => false,
							'addusergroups' => false,
							'addshippingtypes' => false,
							'addcountries' => false,
							'amoduleinoxconfig' => false,
						);
			
			//Installs the tables
			if(!$installer->klarnainstall__createtables->value) {
				$status['createtables'] = $installer->createTables();
			}
			
			//Insersts the payment options
			if(!$installer->klarnainstall__insertpayments->value) {
				$status['insertpayments'] = $installer->insertPayments();
			}
			
			//Adds the user groups needed for the payments
			if(!$installer->klarnainstall__addusergroups->value) {
				$status['addusergroups'] = $installer->addUserGroups();
			}
			
			//Adds the shipping types needed for the payments
			if(!$installer->klarnainstall__addshippingtypes->value) {
				$status['addshippingtypes'] = $installer->addShippingTypes();
			}
			
			//Adds the country types to the payments
			if(!$installer->klarnainstall__addcountries->value) {
				$status['addcountries'] = $installer->addCountries();
			}
			
			//Adds Klarnas extensions to the module extension list
			if(!$installer->klarnainstall__amoduleinoxconfig->value) {
				$status['amoduleinoxconfig'] = $installer->aModuleInOxConfig();
			}
			
			//Adds Klarnas extensions to the module extension list
			if(!$installer->klarnainstall__acurrencies->value) {
				$status['acurrencies'] = $installer->aCurrencies();
			}
			
			$done = true;
			foreach($status as $item) {
				if(!$item) {
					$done = false;
				}
			}
			if($done)
			{
			    oxUtils::getInstance()->redirect("index.php?stoken=".$_GET['stoken']."&cl=klarna_config");
			}
			return $done;
		} catch(Exception $e) {
			$lang = oxLang::getInstance();
			echo $lang->translateString('KLARNA_INSTALLATION_ERROR') . ' &#35;11352';
		}
	}
	
	/**
	 * Make default country. This will not be checked, cause if its not set then
	 * it will be set during the user chooice install.
	 */
	protected function defaultCountry($installer) {	
		if(!$installer->klarnainstall__defaultcountry->value) {
			return $installer->defaultCountry() ? 1 : 0;
		}
		return 1;
	}
	
	/**
	 * Saves the configuration input made in the installation process.
	 */
	public function save() {
		if(!$this->kutil) {
			$this->kutil = oxNew('klarnautil');
		}
		
		$editedKConfigParams = oxConfig::getParameter("kconfedit");
		
		$myConfig  = $this->getConfig();
		$soxId = $myConfig->getShopId();
		
		$kconfig = $this->kutil->getKlarnaConfig();
		if(!$kconfig->klarnaconfig__oxid->rawValue) {
			$kconfig->klarnaconfig__oxid->rawValue = new oxField($soxId, oxField::T_RAW);
		}
		if($kconfig->klarnaconfig__oxid->rawValue) {
			$kconfig->klarnaconfig__currversion->rawValue = $this->kutil->getKredVersion();
			$kconfig->assign($editedKConfigParams);
			$kconfig->save();
			
			$installer = $this->kutil->getInstallObject();
			$installer->klarnainstall__saveconfig->rawValue = 1;
			$installer->klarnainstall__done->rawValue = 1;
			$installer->klarnainstall__acurrencies->rawValue = 1;
			$installer->klarnainstall__defaultcountry->rawValue = 1;
			$installer->save();
			
			$this->kutil->getNewPclasses();
		} else {
			$lang = oxLang::getInstance();
			echo $lang->translateString('KLARNA_INSTALLATION_ERROR') . ' &#35;11364';
		}
	}
}
?>